#!/bin/bash
NAME=rpa_api
ROOT=$(dirname $(readlink -f "$0"))   # ROOT 指向 /path/to/rpa_api/app

PROJECT_ROOT=$(dirname "$ROOT")        # 上一级目录，即 /path/to/rpa_api

mkdir -p "$ROOT/logs"

# 保存 stdout 和 stderr
exec 3>&1 4>&2
exec &> >(tee -a "$ROOT/logs/start-$NAME.log")

./wait-for-it.sh "${MYSQL_HOST:-mysql}:${MYSQL_PORT:-3306}" --timeout=30 --strict -- echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🐬 MySQL is up"
./wait-for-it.sh "${REDIS_HOST:-redis}:${REDIS_PORT:-6379}" --timeout=30 --strict -- echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🟥 Redis is up"

cd "$ROOT/aerich"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🔄 Start migrations check."

if [ -d "migrations" ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 📦 Migrations exist."
    aerich upgrade | while read line; do
        if [[ $line == *"No upgrade items found"* ]]; then
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] ✅ $line"
        else
            echo "[$(date '+%Y-%m-%d %H:%M:%S')] $line"
        fi
    done
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🆕 Migrations not exist."
    aerich init -t env.TORTOISE_ORM
    aerich init-db
fi

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 🚀 uvicorn start"

# 恢复 stdout 和 stderr
exec 1>&3 2>&4

cd "$PROJECT_ROOT"
export PYTHONPATH="$PROJECT_ROOT"

PORT=${1:-5000}
uvicorn app.main:app --host 0.0.0.0 --port $PORT --lifespan on --log-level warning

tail -f /dev/null